const fetch = require('node-fetch')
const moment = require('moment')
const _ = require('lodash/fp')

const api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
const api_token = "http://www.qiyiguo.tv/api/wx/token"

const get_token = () => fetch(api_token).then(res => res.text())

const gen_msg = (need, token) => need.users.map(
    user => {
        const body = `{
            "touser": "${user}",
            "template_id":"93Wkiu0-eSG04hP8Y4tydjhHbX7K5qaqCB4oAXAThQ0",
            "url": "${need.anchor.url}",            
            "data":{
                    "first": {
                        "value":"您关注的主播上线了！"
                    },
                    "keyword1":{
                        "value": "${need.anchor.name}"
                    },
                    "keyword2": {
                        "value":"${need.anchor.room_name}"
                    },
                    "keyword3": {
                        "value":"${moment().format('YYYY年MM月DD日-hh:mm:ss')}"
                    },
                    "remark":{
                        "value":"赶快到他的直播间转转吧！"
                    }
            }
        }`

        //单条推送消息发送失败时，不触发异常
        return new Promise(
            (resolve, reject) => fetch(api + token, {
                method: 'POST',
                body: body
            })
                .then(res => res.json())
                .then(json => { resolve(json); return json })
                .catch(console.error)
        )
    }
)

module.exports = needles =>
    get_token()
        .then(token =>
            Promise.all(_.flattenDeep(needles.map(need => gen_msg(need, token))))
        )
